package halilTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Vector;

public class BootstrapH {
	private static int PORT = 8988;
	 
	private BufferedReader br;
	private String range;
	private DatagramSocket socket;
	private Vector<String> messages;
	private Thread reciever;
	
	public BootstrapH(){
		readConf();
		init();
		reciever = new Thread(new BootstrapReciever(this));
	}
	private void readConf(){
		URL url = getClass().getResource("confFile.txt");
		try {
			File conf = new File(url.toURI());
			InputStreamReader isr = new InputStreamReader(new FileInputStream(conf));
			br = new BufferedReader(isr);
			this.range = br.readLine();
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
	}
	private void init(){
		messages = new Vector<String>();
		try {
			socket = new DatagramSocket(this.PORT, InetAddress.getLocalHost()); // Init server soket
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("Bootstrap info: ");
		sb.append('\n');
		sb.append("    Address: " + socket.getLocalAddress() + ":" + socket.getLocalPort() + '\n');
		sb.append("    Range: " + range);
		return sb.toString();
	}
	public DatagramSocket getSocket() {
		return socket;
	}
	public void addMessage(String message){
		this.messages.add(message);
		System.out.println("Message no." + this.messages.size() + ": " + message);
		reply(message);
	}
	public void reply(String mes){
		String[] message = mes.split(",");

		String address = message[2];
		String m = "HELLO " + address + "";
		byte[] sendData = m.getBytes(); 
		try {
			DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName(address.split(":")[0].substring(1)), Integer.parseInt(address.split(":")[1]));
			socket.send(sendPacket);
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.messages.remove(mes);
	}
	
	
	public static void main(String[] args) {
		BootstrapH b = new BootstrapH();
		b.reciever.start();
		System.out.println(b);	
	}
}
